<?php

namespace App\Services;

use App\Models\CartItem;

class CartService
{
    /**
     * 获取
     *
     * @return mixed
     */
    public function get()
    {
        return \Auth::user()->cartItems()->with(['productSku.product'])->get();
    }

    /**
     * 添加
     *
     * @param $skuId
     * @param $amount
     * @return CartItem
     */
    public function add($skuId, $amount)
    {
        $user = \Auth::user();
        if ($item = $user->cartItems()->where('product_sku_id', $skuId)->first()) {
            $item->update([
                'amount' => $item->amount + $amount,
            ]);
        } else {
            // 否则创建一个新的购物车记录
            $item = new CartItem(['amount' => $amount]);
            $item->user()->associate($user);
            $item->productSku()->associate($skuId);
            $item->save();
        }

        return $item;
    }

    /**
     * 删除
     *
     * @param $skuId
     */
    public function remove($skuId)
    {
        // 可以传入单个 ID 也可以传入 ID数组
        if (!is_array($skuId)) {
            $skuId = [$skuId];
        }
        \Auth::user()->cartItems()->whereIn('product_sku_id', $skuId)->delete();
    }
}